package com.example.tianling.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class RTCUtils {
    private static final Logger logger = LoggerFactory.getLogger(RTCUtils.class);
    private static final String appKey = "c7926083a145206400d05516babf6641";
    private static final String appSecret = "b5ec4365ec91";
    private static final String nonce = "12345";
    // 获取 rtcToken
    public static class DynamicToken {
        public String signature;
        public long curTime;
        public int ttl;
    }
    private String sha1(String input) throws NoSuchAlgorithmException {
        MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
        byte[] result = mDigest.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : result) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    private String getTokenWithCurrentTime(String channelName, long uid, int ttlSec, long curTimeMs) throws Exception {
        //生成 signature，将 appkey、uid、curTime、ttl、appsecret 五个字段拼成一个字符串，进行 sha1 编码
        DynamicToken tokenModel = new DynamicToken();
        tokenModel.signature = sha1(String.format("%s%d%d%d%s%s", appKey, uid, curTimeMs, ttlSec, channelName, appSecret));
        tokenModel.curTime = curTimeMs;     //获取当前时间戳，单位为毫秒
        tokenModel.ttl = ttlSec;      //设置Token的过期时间，单位为秒
        ObjectMapper objectMapper = new ObjectMapper();
        String signature = objectMapper.writeValueAsString(tokenModel);
        return Base64.getEncoder().encodeToString(signature.getBytes(StandardCharsets.UTF_8));   // 对JSON字符串进行Base64编码，返回生成的Token字符串
    }
    public String getToken(String channelName, long uid, int ttlSec) throws Exception {
        long curTimeMs = System.currentTimeMillis();
        return getTokenWithCurrentTime(channelName, uid, ttlSec, curTimeMs);
    }

    private String getCheckSum(String appSecret, String nonce, long curTime) throws NoSuchAlgorithmException {
        return sha1(appSecret + nonce + curTime);
    }
    // 开启云端录制
    public String startCloudRecord(String roomId) throws IOException, NoSuchAlgorithmException {
        String url = "https://logic-dev.netease.im/v3/api/cloudrecord/submit?cname="+roomId;

        OkHttpClient client = new OkHttpClient();

        // 设置头部
        long curTime = (new Date()).getTime() / 1000L;
        String checkSum = getCheckSum(appSecret, nonce ,curTime);

        JSONObject jsonObject = new JSONObject();

        Map<String, Integer> recordType = new HashMap<>();
        recordType.put("recordtype", 1);
        jsonObject.put("recordConfig",recordType);
        RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json;charset=utf-8"));

        Request request = new Request.Builder()
                .addHeader("AppKey", appKey)
                .addHeader("Nonce", nonce)
                .addHeader("CurTime", String.valueOf(curTime))
                .addHeader("CheckSum", checkSum)
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        logger.info("房间{}录制的响应码：{}", roomId, response.code());
//        logger.info(response.body().string());


        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            JSONObject record = (JSONObject) responseJson.get("record");

            return record.getString("taskId");
        }
        return "";
    }

    public String stopCloudRecord(String roomId, String taskId) throws IOException, NoSuchAlgorithmException {
        String url = "https://logic-dev.netease.im/v3/api/cloudrecord/stop?cname="+roomId;

        OkHttpClient client = new OkHttpClient();

        // 设置头部
        long curTime = (new Date()).getTime() / 1000L;
        String checkSum = getCheckSum(appSecret, nonce ,curTime);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("taskId",taskId);
        RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json;charset=utf-8"));

        Request request = new Request.Builder()
                .addHeader("AppKey", appKey)
                .addHeader("Nonce", nonce)
                .addHeader("CurTime", String.valueOf(curTime))
                .addHeader("CheckSum", checkSum)
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        logger.info("房间{}录制的响应码：{}", roomId, response.code());
//        logger.info(response.body().string());


        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            JSONObject record = (JSONObject) responseJson.get("record");

            return record.getString("taskId");
        }
        return "";
    }

}
